package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.*;
import cn.wolfcode.crm.mapper.CarMapper;
import cn.wolfcode.crm.mapper.ClientMapper;
import cn.wolfcode.crm.mapper.InsureInfoMapper;
import cn.wolfcode.crm.mapper.ProductItemMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IInsureInfoService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class InsureInfoServiceImpl implements IInsureInfoService {
    @Autowired
    private InsureInfoMapper insureInfoMapper;
    @Autowired
    private ProductItemMapper itemMapper;
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private ClientMapper clientMapper;

    public void saveOrUpdate(InsureInfo entity) {
        if (entity.getId() == null) {
            insert(entity);
        } else {
            update(entity);
        }
    }

    private void update(InsureInfo entity) {
        Car car = entity.getCar();
        //更新车辆信息
        carMapper.updateByPrimaryKey(car);
        //删除原来对应保单id的产品明细
        itemMapper.deleteByInsureId(entity.getId());
        //重新计算投保金额
        //设置投保金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (Product p : entity.getProducts()) {
            totalAmount = totalAmount.add(p.getAnnualFee());
            //新建一个产品明细
            ProductItem item = new ProductItem();
            item.setInsureinfoId(entity.getId());
            item.setOrganizationId(entity.getOrganization().getId());
            item.setProductId(p.getId());
            itemMapper.insert(item);
        }
        entity.setTotalAmount(totalAmount.multiply(new BigDecimal(entity.getTime())));
        //更新保单
        insureInfoMapper.updateByPrimaryKey(entity);
    }

    private void insert(InsureInfo entity) {
        Car car = entity.getCar();
        //新增车辆信息
        carMapper.insert(car);
        //设置申请日期
        entity.setApplyDate(new Date());
        //设置表单编号
        Calendar c = Calendar.getInstance();
        StringBuilder sb = new StringBuilder(20);
        sb.append(c.get(Calendar.YEAR)).append(c.get(Calendar.MONTH)).append(c.get(Calendar.DAY_OF_MONTH));
        for (int i = 0; i < 5; i++) {
            sb.append(new Random().nextInt(10));
        }
        entity.setSn(sb.toString());
        //设置业务员
        entity.setInputUser(UserContext.getCurrentUser());
        //设置投保金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (Product p : entity.getProducts()) {
            totalAmount = totalAmount.add(p.getAnnualFee());
        }
        entity.setTotalAmount(totalAmount.multiply(new BigDecimal(entity.getTime())));
        //新增保单
        insureInfoMapper.insert(entity);
        //获取保单id
        Long infoId = entity.getId();
        //新增产品明细
        entity.getProducts().forEach(p -> {
            //新建一个产品明细
            ProductItem item = new ProductItem();
            item.setInsureinfoId(infoId);
            item.setOrganizationId(entity.getOrganization().getId());
            item.setProductId(p.getId());
            itemMapper.insert(item);
        });

    }

    public void delete(Long id) {
        insureInfoMapper.deleteByPrimaryKey(id);
    }

    public InsureInfo get(Long id) {
        return insureInfoMapper.selectByPrimaryKey(id);
    }

    public List<InsureInfo> listAll() {
        return insureInfoMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        int count = insureInfoMapper.queryCount(qo);
        if (count == 0) {
            return new PageResult(0, Collections.emptyList());
        }
        List<InsureInfo> insureInfos = insureInfoMapper.queryList(qo);
        return new PageResult(count, insureInfos);
    }

    @Override
    public void changeState(Long id,Integer state) {
        //通过id查询对应的保单
        InsureInfo info = insureInfoMapper.selectByPrimaryKey(id);
        //调整状态
        info.setState(state);
        //更新信息
        insureInfoMapper.changeState(info);
        //如果是审核,更新审核时间
        if (state == InsureInfo.UNPAY){
            info.setAuditDate(new Date());//审核时间
            info.setAuditUser(UserContext.getCurrentUser());
            insureInfoMapper.audit(info);
        }
    }

    @Override
    public void amend(Long id, Integer state, String opinion) {
        //通过id查询对应的保单
        InsureInfo info = insureInfoMapper.selectByPrimaryKey(id);
        //调整状态
        info.setState(state);
        info.setOpinion(opinion);
        //更新信息
        insureInfoMapper.amend(info);
    }


    public List<InsureInfo> listAllForClaimsClientDetails() {

        return insureInfoMapper.listAllForClaimsClientDetails();
    }

    @Override
    public void pay(InsureInfo info) {
        //通过传过来的id查询出完整的保单信息
        InsureInfo entity = insureInfoMapper.selectByPrimaryKey(info.getId());
        //客户转正
        Client client = entity.getClient();
        //判断客户有没有负责人
        Client c = clientMapper.selectByPrimaryKey(client.getId());
        if (c.getChargeuser() == null){
            c.setChargeuser(entity.getInputUser());
            clientMapper.exploit(c);
        }
        //把客户设置为正式客户
        clientMapper.upgrade(client.getId());
        //获取车辆信息
        Car car = entity.getCar();
        //把车辆的信息设置为投保状态
        carMapper.upgrade(car.getId());
        //设置保单的一些状态
        entity.setPayMethod(info.getPayMethod());
        entity.setBeginDate(info.getBeginDate());
        //推算出保单的结束时间
        Calendar instance = Calendar.getInstance();
        instance.setTime(entity.getBeginDate());
        //加两年
        instance.add(Calendar.YEAR,entity.getTime());
        //设置进结束时间
        entity.setEndDate(instance.getTime());
        //吧保单的状态修改为已缴费状态
        entity.setState(InsureInfo.FINISH);
        //更新保单信息
        insureInfoMapper.pay(entity);
    }
}
